package com.cskaoyan.market.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

//@Component
public class MarketAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        MarketToken token = (MarketToken) authenticationToken;
        // admin wx
        String type = token.getType();
        Collection<Realm> realms = getRealms();
        List<Realm> qualifiedRealms = new ArrayList<>();
        for (Realm realm : realms) {
            if(realm.getName().toLowerCase().contains(type)){
                qualifiedRealms.add(realm);
            }
        }

        if (qualifiedRealms.size() == 1) {
            return doSingleRealmAuthentication(qualifiedRealms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(qualifiedRealms, authenticationToken);
        }
    }
}
